/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package iodegree.lib.pattern;

import iodegree.circuitTable.CircuitTableFrame;
import iodegree.lib.MyTableModel;
import iodegree.lib.CommonsLib;
import iodegree.lib.D;
import iodegree.lib.StatisticsConversion;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import javax.swing.JFileChooser;
import org.apache.commons.math3.stat.descriptive.SummaryStatistics;

/**
 *
 * @author Libra
 */
public class PatternUI extends javax.swing.JFrame {

    /**
     * Creates new form SplitUI
     */
    public PatternUI() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        DataFileChooser = new javax.swing.JFileChooser();
        btnGrp = new javax.swing.ButtonGroup();
        jPanel1 = new javax.swing.JPanel();
        btnGenRndM2 = new javax.swing.JButton();
        jLabel7 = new javax.swing.JLabel();
        btnOpenDatabase = new javax.swing.JButton();
        lblOpenDatabase = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        txtCycles = new javax.swing.JTextField();
        btnOpenDbDefault = new javax.swing.JButton();
        btnDrawPatt = new javax.swing.JButton();
        rdoBoth = new javax.swing.JRadioButton();
        rdoGluOnly = new javax.swing.JRadioButton();
        rdoGABAOnly = new javax.swing.JRadioButton();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        jPanel3 = new javax.swing.JPanel();
        statsPanel = new javax.swing.JScrollPane();
        statsTable = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        btnGenRndM2.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnGenRndM2.setText("Generate Random");
        btnGenRndM2.setEnabled(false);
        btnGenRndM2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGenRndM2ActionPerformed(evt);
            }
        });

        jLabel7.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        jLabel7.setText("Random Sim :");

        btnOpenDatabase.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnOpenDatabase.setText("Open");
        btnOpenDatabase.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenDatabaseActionPerformed(evt);
            }
        });

        lblOpenDatabase.setFont(new java.awt.Font("Tahoma", 0, 14)); // NOI18N
        lblOpenDatabase.setText("Open Database File :");

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel8.setText("Cycles");

        txtCycles.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        txtCycles.setText("1000");
        txtCycles.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtCyclesActionPerformed(evt);
            }
        });

        btnOpenDbDefault.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnOpenDbDefault.setText("Default");
        btnOpenDbDefault.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOpenDbDefaultActionPerformed(evt);
            }
        });

        btnDrawPatt.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        btnDrawPatt.setText("Draw");
        btnDrawPatt.setEnabled(false);
        btnDrawPatt.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDrawPattActionPerformed(evt);
            }
        });

        btnGrp.add(rdoBoth);
        rdoBoth.setSelected(true);
        rdoBoth.setText("Both");

        btnGrp.add(rdoGluOnly);
        rdoGluOnly.setText("Glu Only");

        btnGrp.add(rdoGABAOnly);
        rdoGABAOnly.setText("GABA Only");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(txtCycles, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(18, 18, 18)
                        .addComponent(jLabel8)
                        .addGap(18, 18, 18)
                        .addComponent(btnGenRndM2))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(lblOpenDatabase)
                        .addGap(18, 18, 18)
                        .addComponent(btnOpenDatabase)
                        .addGap(18, 18, 18)
                        .addComponent(btnOpenDbDefault)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(btnDrawPatt)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(rdoBoth)
                        .addGap(18, 18, 18)
                        .addComponent(rdoGluOnly)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(rdoGABAOnly)))
                .addGap(57, 57, 57))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnOpenDatabase)
                    .addComponent(btnOpenDbDefault)
                    .addComponent(lblOpenDatabase)
                    .addComponent(rdoBoth)
                    .addComponent(rdoGluOnly)
                    .addComponent(rdoGABAOnly))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel7)
                    .addComponent(jLabel8)
                    .addComponent(txtCycles, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnGenRndM2)
                    .addComponent(btnDrawPatt))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        statsTable.setAutoResizeMode(javax.swing.JTable.AUTO_RESIZE_OFF);
        statsPanel.setViewportView(statsTable);

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statsPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 635, Short.MAX_VALUE)
                .addContainerGap())
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel3Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(statsPanel, javax.swing.GroupLayout.PREFERRED_SIZE, 358, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(27, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Stats", jPanel3);

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 655, Short.MAX_VALUE)
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 396, Short.MAX_VALUE)
        );

        jTabbedPane1.addTab("Details", jPanel2);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jTabbedPane1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jTabbedPane1)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void getSimPattCount(int genCycle) {
        Pattern patt = new Pattern();
        int type = rdoBoth.isSelected() ? 0
                : rdoGluOnly.isSelected() ? 1 : 2;
        ArrayList<int[]> tripletIds;
        SummaryStatistics[] sums = new SummaryStatistics[nPattern];
        SummaryStatistics coeStats = new SummaryStatistics();
        PattList conns = new PattList(pathToFile);
        conns.init();
        for (int i = 0; i < sums.length; i++) {
            sums[i] = new SummaryStatistics();
        }

        tripletIds = conns.getIdList();

        for (int cy = 0; cy < genCycle; cy++) {
            HashMap<Integer, Boolean> map = conns.getSimMap();
            int patCount[] = new int[nPattern];
            for (int i = 0; i < tripletIds.size(); i++) {
                patCount[patt.triPatId(tripletIds.get(i), type, map)]++;
            }
            //coe
            coeStats.addValue(coe(patCount));
//            int totalPattTypes = 0;
            for (int i = 0; i < nPattern; i++) {
//                totalPattTypes += patCount[i] == 0 ? 0 : 1;
                sums[i].addValue(patCount[i]);
            }
//            D.tp(totalPattTypes);
        }
        exp = new double[obs.length];
        prob = new double[obs.length];

        Object[][] sumsTable = new Object[nPattern + 1][6];
        sumsTable[0][0] = "ID";
        sumsTable[0][1] = "OBS";
        sumsTable[0][2] = "EXP";
        sumsTable[0][3] = "S.D.";
        sumsTable[0][4] = "p";
        sumsTable[0][5] = "(O-E)/E";

        for (int i = 0; i < nPattern; i++) {
            int j = i + 1;
            sumsTable[j][0] = new Integer(i);
            sumsTable[j][1] = new Integer(obs[i]);
            exp[i] = sums[i].getMean();
            sumsTable[j][2] = new Double(exp[i]);
            sumsTable[j][3] = new Double(sums[i].getStandardDeviation());
            double zScore = (double) (obs[i] - sums[i].getMean()) / sums[i].getStandardDeviation();
            prob[i] = StatisticsConversion.twoTailPvalue(zScore);
            sumsTable[j][4] = new Double(prob[i]);
            sumsTable[j][5] = new Double((obs[i] - exp[i]) / exp[i]);
        }

        MyTableModel transTable = new MyTableModel(sumsTable);
        statsPanel.setColumnHeaderView(null);
        statsTable.setModel(transTable);
        
        D.tp(coeStats.getN(),coeStats.getMean(),coeStats.getStandardDeviation());
    }

    private void getObsPattCount() {
        PattList conns = new PattList(pathToFile);
        HashMap<Integer, Boolean> map = conns.getObsMap();
        Pattern patt = new Pattern();
        ArrayList<int[]> pattList = conns.getIdList();

        int type = rdoBoth.isSelected() ? 0
                : rdoGluOnly.isSelected() ? 1 : 2;

        TriPattLib tlist = new TriPattLib();
        nPattern = tlist.getnPatt();
        int patCount[] = new int[nPattern];
        for (int i = 0; i < pattList.size(); i++) {
            patCount[patt.triPatId(pattList.get(i), type, map)]++;
        }
        obs = patCount;

        //Fill Table
        Object[][] sumsTable = new Object[nPattern + 1][2];
        sumsTable[0][0] = "ID";
        sumsTable[0][1] = "OBS";
        for (int i = 0; i < nPattern; i++) {
            int j = i + 1;
            sumsTable[j][0] = new Integer(i);
            sumsTable[j][1] = new Integer(obs[i]);
        }
        MyTableModel transTable = new MyTableModel(sumsTable);
        statsPanel.setColumnHeaderView(null);
        statsTable.setModel(transTable);

    }

    private float coe(int[] pattCounts) {
        int connedTriplet = 0;
        int triangle = 0;
        for (int i = 6; i < 32; i++) {
            connedTriplet += pattCounts[i];
        }
        for (int i = 33; i < pattCounts.length; i++) {
            connedTriplet += pattCounts[i] * 3;
            triangle += pattCounts[i] * 3;
        }
        return (float) triangle / connedTriplet;
    }

    private void btnOpenDbDefaultActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenDbDefaultActionPerformed
        pathToFile = CommonsLib.getDefaultFile();
        File f = new File(pathToFile);
        if (f.exists()) {
            getObsPattCount();
            btnGenRndM2.setEnabled(true);
            btnDrawPatt.setEnabled(false);
        }
    }//GEN-LAST:event_btnOpenDbDefaultActionPerformed

    private void btnOpenDatabaseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOpenDatabaseActionPerformed
        int returnVal = DataFileChooser.showOpenDialog(this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            pathToFile = DataFileChooser.getSelectedFile().getAbsolutePath();
            getObsPattCount();
            btnGenRndM2.setEnabled(true);
            btnDrawPatt.setEnabled(false);
        }
    }//GEN-LAST:event_btnOpenDatabaseActionPerformed

    private void txtCyclesActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtCyclesActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtCyclesActionPerformed

    private void btnGenRndM2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGenRndM2ActionPerformed
        getSimPattCount(Integer.parseInt(txtCycles.getText()));
        btnDrawPatt.setEnabled(true);
    }//GEN-LAST:event_btnGenRndM2ActionPerformed

    private void btnDrawPattActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDrawPattActionPerformed

        CircuitTableFrame ui = new CircuitTableFrame();
        ui.setObs(obs);
        ui.setExp(exp);
        ui.setProb(prob);
        ui.init();
        ui.setVisible(true);
    }//GEN-LAST:event_btnDrawPattActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;


                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(PatternUI.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new PatternUI().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JFileChooser DataFileChooser;
    private javax.swing.JButton btnDrawPatt;
    private javax.swing.JButton btnGenRndM2;
    private javax.swing.ButtonGroup btnGrp;
    private javax.swing.JButton btnOpenDatabase;
    private javax.swing.JButton btnOpenDbDefault;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JLabel lblOpenDatabase;
    private javax.swing.JRadioButton rdoBoth;
    private javax.swing.JRadioButton rdoGABAOnly;
    private javax.swing.JRadioButton rdoGluOnly;
    private javax.swing.JScrollPane statsPanel;
    private transient javax.swing.JTable statsTable;
    private javax.swing.JTextField txtCycles;
    // End of variables declaration//GEN-END:variables
    private String pathToFile;
    private int nPattern;
    private int obs[];
    private double exp[];
    private double prob[];
}
